package com.mk.common;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 4:33 PM 3/15/18
 */
public class FileUploadUtil {

    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file,String fileUploadPath){
        String url = null;
        try{
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;
            File f = new File(fileUploadPath);
            if(!f.exists())
                f.mkdirs();
            System.out.println(f.getAbsolutePath());
            File serverFile = new File(fileUploadPath + fileName);
            file.transferTo(serverFile);
            url = fileName;
        }catch (IOException e){
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 复制单个文件
     * @param oldFile
     * @return
     */
    public static String copyOneFile(File oldFile,String fileUploadPath){
        String fileName = null;
        InputStream is = null;
        FileOutputStream fs = null;
        try{
            String suffix = oldFile.getName().substring(oldFile.getName().lastIndexOf("."));
            fileName = UUID.randomUUID().toString() + suffix;
            String newPath = fileUploadPath + fileName;
            int byteSum = 0;
            int byteRead = 0;
            if(oldFile.exists()){//原来的文件存在
                //读取源文件
                is = new FileInputStream(oldFile.getAbsoluteFile());
                fs = new FileOutputStream(newPath);
                byte[] buff = new byte[1444];
                while ((byteRead = is.read(buff)) != -1){
                    byteSum += byteRead;//最终的文件大小
                    System.out.println("..." + byteSum);
                    fs.write(buff,0,byteRead);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(fs != null)
                    fs.close();
                if(is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    /**
     * 传入图片的完整路径来删除图片
     * @param filePath
     */
    public static void deleteImage(String filePath){
        try {
            File file = new File(filePath);
            if (file.exists())
                file.delete();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
